﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml.Linq;
using JMT.Data.Serializer;

namespace JMT.Data
{
    public class JMSolutionStore
    {
        public string Path { get; set; }

        #region save
        public void Save(JSolution solution)
        {
            SaveAs(solution, Path);
        }

        public void SaveAs(JSolution solution, string path)
        {
            FileInfo fileInfo = new FileInfo(path);
            string filePath = path;// Path.Combine(path, string.Format("{0}.xml", solution.Name));

            if (!fileInfo.Directory.Exists)
            {
                Directory.CreateDirectory(fileInfo.Directory.FullName);
            }

            XDocument xDoc = new XDocument();
            XElement xJMT = new XElement("jmt");
            xJMT.Add(new XAttribute("version", "1.1"));

            JModelSerializer serializer = JSerializerFactory.Get(solution.Type);
            serializer.Serialize(xJMT, solution);
            
            // 保存新建model的seed
            XElement xSeeds = new XElement("seed");
            foreach (Type type in JData.Current.NameCreator.Seeds.Keys)
            {
                string typeName = JConstString.GetType(type);
                XElement xSeed = new XElement(typeName);
                xSeed.Add(new XAttribute("value", JData.Current.NameCreator.Seeds[type]));
                xSeeds.Add(xSeed);
            }
            xJMT.Add(xSeeds);

            xDoc.Add(xJMT);
            xDoc.Save(filePath);

            this.Path = filePath;
        }
        #endregion

        #region load
        public JSolution Load(string path)
        {
            XDocument xDoc = XDocument.Load(path);

            XElement xJMT = xDoc.Element("jmt");

            XElement xs = xJMT.Elements().First();
            JModelSerializer serializer = JSerializerFactory.Get(xs.Name.LocalName);
            JSolution solution = (JSolution)serializer.Deserialize(xs);

            // 读取seed
            List<XElement> xSeeds = xJMT.Element("seed").Elements().ToList();
            JData.Current.NameCreator = new ModelNameCreator();
            foreach (var xSeed in xSeeds)
            {
                string typeName = xSeed.Name.LocalName;
                Type modelType = JConstString.GetModelType(typeName);
                int seed = Convert.ToInt32(xSeed.Attribute("value").Value);
                JData.Current.NameCreator.Seeds.Add(modelType, seed);
            }

            this.Path = path;
            return solution;
        }
        #endregion
    }
}
